import { Button, Drawer, Alert, message, Space, Switch, Form, Checkbox, Radio, Tabs } from "antd";
import React, { useEffect, useState } from "react";
import HeaderTab from "@/components/CommonTab/index";
import SubTitle from "@/pages/OrderModule/common/components/SubTitle";
import Style from "./index.module.less";
import "./index.css";
import { getSuggestruleconfig, saveSuggestruleconfig } from "../../../service";
import { cloneDeep } from "lodash";
import CommonDrawer from '@/components/CommonDrawer';
import { DialogEnum } from "../index";
const MAP = {
	["0"]: "purchasedAdviceSold",
	["1"]: "inventoryPurchaseProposal"
};
const defaultType = "0";
const RuleSettings = ({ onCancel, actionName, setActionName, tabArr }) => {
	const [type, setType] = useState(defaultType);
	// 配置数据
	const [config, setConfig] = useState({});
	const [form] = Form.useForm();
	const onSave = () => {
		form.submit();
	};
	const onFinish = () => {
		const API_DATA = form.getFieldsValue();

		API_DATA["returnWarehouse"] = API_DATA["returnWarehouse"][0];
		API_DATA["defectiveWarehouse"] = API_DATA["defectiveWarehouse"][0];
		API_DATA["type"] = Number(type);
		saveSuggestruleconfig(API_DATA).then(res => {
			const { success } = res;
			if (success) {
				message.success("操作成功");
				onCancel();
			}
		});
	};
	useEffect(() => {
		setType(defaultType);
		form.resetFields();
		if (actionName === DialogEnum.RuleSettings) {
			getSuggestruleconfig().then(res => {
				const { data = {}, success } = res;
				if (success) {
					// 处理数据
					const obj = {};
					Object.keys(cloneDeep(data) || {}).forEach(key => {
						const obj1 = {};
						Object.keys(data[key]).forEach(key2 => {
							const value = data[key][key2];
							obj1[key2] = value == null ? Number(value) : value;
						});
						obj[key] = {
							...obj1,
							// 销退仓
							returnWarehouse: [data[key]?.returnWarehouse],
							// // 次品仓
							defectiveWarehouse: [data[key]?.defectiveWarehouse]
						};
					});

					console.log("obj", obj);
					setConfig(obj);
				}
			});
		}
	}, [actionName]);
	// 监听配置数据和tabs变化更新配置数据

	useEffect(() => {
		form.resetFields();
		form.setFieldsValue(config[MAP[type]]);
	}, [config, type]);

	// 组件获取值后进行转换，再放入 Form 中。不支持异步
	const normalize = value => {
		return Number(value);
	};

	return (
		<CommonDrawer
			title={<span className={Style.title}>采购规则设置</span>}
			width="60%"
			placement="right"
			onClose={onCancel}
			open={Boolean(actionName === DialogEnum.RuleSettings)}
			footer={
				<>
					<Button
						type="primary"
						onClick={onSave}
						style={{ width: "64px", height: "32px", fontSize: 14, padding: "0", textAlign: "center" }}
					>
						保存设置
					</Button>
				</>
			}
			footerStyle={{ display: "flex", justifyContent: "flex-end" }}
		>
			<Form form={form} className="RuleSettingsDrawer" onFinish={onFinish}>
				<Tabs
					activeKey={type}
					onChange={val => {
						setType(val);
					}}
					className="rule-reset"
					items={tabArr.map(item => {
						return {
							label: item.tab,
							key: item.key
						};
					})}
				/>
				<Alert
					message={
						<Space size={8} direction="vertical">
							{type == "0" && (
								<>
									<div className={Style["alert-item"]}>计算公式：建议采购数 = 订单待发 - 仓库库存数</div>
									<div className={Style["alert-item"]}>{`触发条件： 仓库库存数 - 订单待发 < 0`}</div>
								</>
							)}
							<div className={Style["alert-item"]}>
								注：仓库库存数 = 发货仓库存数 + 销退仓库存(可选项) + 采购在途(可选项) + 次品仓库存(可选项)
							</div>
						</Space>
					}
					type="info"
					showIcon
					style={{ marginBottom: "32px" }}
				/>
				{type == "1" && (
					<>
						<SubTitle
							title={
								<div style={{ lineHeight: "21px" }}>
									<span>以下触发条件只能选择一种</span>
								</div>
							}
							as="s2"
							symbol
						/>
						<div>
							<p className={Style.label}>
								<span style={{ color: "#FF3838" }}>触发条件1</span>
								{`∶仓库库存数-订单待发<=安全库存下限`}
							</p>
							<Form.Item name="safeStock" normalize={normalize}>
								<Radio.Group>
									<Radio value={1}>采购 至 安全库存上限</Radio>
									<br />
									<Radio value={2} style={{ marginTop: 14 }}>
										采购 至 安全库存下限
									</Radio>
									<p className={Style.label}>
										<span style={{ color: "#FF3838" }}>触发条件2</span>
										{`∶仓库库存数-订单待发<=安全库存上限`}
									</p>
									<Radio value={3}>采购 至 安全库存上限</Radio>
								</Radio.Group>
							</Form.Item>
							{/* <Form.Item name="conditionsOneFloor" normalize={normalize}>
								<Radio.Group>
									
								</Radio.Group>
							</Form.Item> */}
							{/* <p className={Style.label}>
								<span style={{ color: "#FF3838" }}>触发条件2</span>
								{`∶仓库库存数-订单待发<=安全库存上限`}
							</p>
							<Form.Item name="conditionsTwoUpperLimit" normalize={normalize}>
								<Radio.Group>
									<Radio value={1}>采购 至 安全库存上限</Radio>
								</Radio.Group>
							</Form.Item> */}
						</div>
					</>
				)}
				<SubTitle
					title={
						<div style={{ lineHeight: "21px" }}>
							<span>仓库库存数设置</span> <span style={{ color: "#666666" }}>(勾选以下，仓库库存数计算时计算对应库存数)</span>
						</div>
					}
					as="s2"
					symbol
				/>
				<div>
					<p className={Style.label}>发货仓：</p>
					<Form.List name="configList">
						{(fields, { add, remove }) => (
							<Space className={Style.box} size={15} direction="vertical">
								{fields.map((field, index) => {
									const item = form.getFieldValue("configList")[index];
									return (
										<Form.Item key={item.id} name={[field.name, "checked"]} noStyle className={Style["form-item"]}>
											<Checkbox
												defaultChecked={item?.checked === 1}
												disabled={item?.isDefault === 0}
												className={Style["checkbox"]}
												onChange={e => {
													form.getFieldValue("configList")[index].checked = Number(e.target.checked);
												}}
											>
												<span className={Style["checkbox-label"]}>{item.name}</span>
											</Checkbox>
										</Form.Item>
									);
								})}
							</Space>
						)}
					</Form.List>
					{}
					<p className={Style.label}>销退仓：</p>
					<Form.List name="returnWarehouse">
						{(fields, { add, remove }) => (
							<Space className={Style.box} size={15} direction="vertical">
								{fields.map((field, index) => {
									const item = form.getFieldValue("returnWarehouse")[index];
									return item.name ? (
										<Form.Item key={item.id} {...field} name={[field.name, "checked"]} noStyle className={Style["form-item"]}>
											<Checkbox
												defaultChecked={item?.checked === 1}
												onChange={e => {
													form.getFieldValue("returnWarehouse")[index].checked = Number(e.target.checked);
												}}
												className={Style["checkbox"]}
											>
												{item?.name}
											</Checkbox>
										</Form.Item>
									) : (
										<></>
									);
								})}
							</Space>
						)}
					</Form.List>

					<p className={Style.label}>次品仓：</p>
					<Form.List name="defectiveWarehouse">
						{(fields, { add, remove }) => (
							<Space className={Style.box} size={15} direction="vertical">
								{fields.map((field, index) => {
									const item = form.getFieldValue("defectiveWarehouse")[index];
									return item.name ? (
										<Form.Item key={item.id} {...field} name={[field.name, "checked"]} noStyle className={Style["form-item"]}>
											<Checkbox
												defaultChecked={item?.checked === 1}
												onChange={e => {
													form.getFieldValue("defectiveWarehouse")[index].checked = Number(e.target.checked);
												}}
												className={Style["checkbox"]}
											>
												{item?.name}
											</Checkbox>
										</Form.Item>
									) : (
										<></>
									);
								})}
							</Space>
						)}
					</Form.List>
					<p style={{ marginTop: "29px" }}>
						<span>是否考虑采购在途数据：</span>
						<Form.Item name="purchasingInTransit" noStyle valuePropName="checked" normalize={normalize}>
							<Switch style={{ marginRight: "12px" }} />
						</Form.Item>
						<span>快消采购与采购单均包含在内</span>
					</p>
				</div>
			</Form>
		</CommonDrawer>
	);
};

export default RuleSettings;
